
#include <stdint.h>
#include <cstring>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/socket.h>
#include <iostream>
#include <unistd.h>
#include <thread>
#
#include "log.hpp"
#include "task.hpp"
namespace Server
{
    using namespace std;
    class server
    {
    public:
        server(uint16_t port) : _listenSock(-1), _sock(-1), _port(port)
        {}

        void initServe()
        {
            _listenSock = socket(AF_INET, SOCK_STREAM, 0);
            sockaddr_in local;
            bzero(&local, sizeof(local));
            local.sin_family = AF_INET;
            local.sin_addr.s_addr = INADDR_ANY;
            local.sin_port = htons(_port);
            if (bind(_listenSock, (sockaddr *)&local, sizeof(local)) < 0)
            {
                std::cout << "bind socket error" << std::endl;
                exit(-1);
            }

            // 3.将套接字设为监听状态
            if (listen(_listenSock, 5) < 0)
            {
                std::cout << "listen socket error" << std::endl;
                exit(-1);
            }
        }
        void start()
        {
            //获取新套接字
            while (true)
            {
                sockaddr_in peer; // 用于记录客户端的网络信息
                socklen_t peerLen = sizeof(peer);

                int tcpSock = accept(_listenSock, (sockaddr *)&peer, &peerLen);
                //多进程
                // pid_t id = fork();
                // if (id == 0) // child
                // {
                //     close(_listenSock);
                //     if(fork()>0) exit(0);//关闭子进程，让io在孙子进程中跑，以达到进程分离
                //     serviceIO(tcpSock);                  
                //     exit(0);
                // }
                // close(tcpSock);
                //多线程
                std::unique_ptr<std::thread> conn(new std::thread(serviceIO,tcpSock));
                logMessage(DEBUG,"new thread sucess");
                conn->detach();
            }
        }
        uint16_t _port;
        int _listenSock;
        int _sock;
    };
} // namespace Server
